package com.sunny.blog.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.sunny.blog.common.annotation.RequiredLogin;
import com.sunny.blog.service.FileService;
import com.sunny.blog.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ClassName: FileUploadController
 * @Description:
 * @Author: sunt
 * @Date: 2020/4/13 19:43
 * @Version 1.0
 **/
@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;
    @Value("${upload.path}")
    private String uploadPath;
    @Value("${upload.url}")
    private String uploadUrl;
    @ResponseBody
    @RequestMapping("/uploadFdfsFile")
    public String uploadFdfsFile(HttpSession session, @RequestParam(value = "editormd-image-file") MultipartFile file) {
        JSONObject res = new JSONObject();
        try {
            String uploadFile = fileService.uploadFdfsFile(file);
            byte[] fileByte = file.getBytes();
            String fileName = file.getOriginalFilename();
            res.put("success", 1);
            res.put("message", "上传成功");
            res.put("url", "http://10.93.15.47/" + uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传图片异常", e);
            res.put("success", 0);
            res.put("message", "上传异常");
        }
        log.info("上传图片返回结果：{}", res);
        return res.toString();
    }

    @ResponseBody
    @RequestMapping("/uploadImage")
    @RequiredLogin(required = true)
    public String uploadImage(@RequestParam(value = "editormd-image-file") MultipartFile file) {
        JSONObject res = new JSONObject();
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = StrUtil.subSuf(originalFilename,originalFilename.lastIndexOf("."));
            String newFileName = CommonUtil.genId() + suffix;
            File uploadFile = FileUtil.writeBytes(file.getBytes(), uploadPath + newFileName);
           // ImgUtil.pressText(file.getInputStream(),FileUtil.getOutputStream(FileUtil.newFile(uploadPath + newFileName)),"来源:sunnyBlog"
            //, Color.ORANGE,new Font("宋体", Font.PLAIN, 14),0,14,0.5f);
            if(uploadFile.length() > 0) {
                res.put("success", 1);
                res.put("message", "上传成功");
                res.put("url", uploadUrl + newFileName);
                return res.toString();
            }else {
                res.put("success", 0);
                res.put("message", "上传失败,请重试");
                return  res.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传图片异常", e);
            res.put("success", 0);
            res.put("message", "上传异常");
            return res.toString();
        }
    }


    /**
     * 在线预览图片
     */
    @RequestMapping("/viewImage")
    @ResponseBody
    @RequiredLogin(required = true)
    public void viewImage(HttpServletRequest request, HttpServletResponse response, String key) {
        BufferedInputStream bis = null;
        OutputStream os = null;
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");
       // byte[] file = messageStoreService.loadBytes(key);
        try {
            os = response.getOutputStream();
           // os.write(file);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
